package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.service.Service.CategoryService;
import com.itheima.service.Service.DishService;
import com.itheima.service.Service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @GetMapping("/page")
    public R page(HttpServletRequest httpServletRequest,int page,int pageSize){
        Page<Category> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,lqw);
        return R.success(pageInfo);
    }
    @PostMapping()
    public R save(@RequestBody Category category){
        categoryService.save(category);
       if (categoryService.getById(category.getId())!=null){
           return R.success("添加成功");
       }else {
            return R.error("添加失败");
       }
//        return R.success("添加成功");
    }
@DeleteMapping()
    public R delete(Long id){
    LambdaQueryWrapper<Dish> lqwDis=new LambdaQueryWrapper<>();
    lqwDis.eq(Dish::getCategoryId,id);
    LambdaQueryWrapper<Setmeal> lqwSetm=new LambdaQueryWrapper<>();
    lqwSetm.eq(Setmeal::getCategoryId,id);
   setmealService.getMap(lqwSetm);
    if (setmealService.getMap(lqwSetm)!=null||dishService.getMap(lqwDis)!=null){
        return R.error("删除失败");
    }
    LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
    lqw.eq(Category::getId,id);
    categoryService.remove(lqw);
    if (categoryService.getById(id)!=null){
        return R.error("删除失败");
    }else {
        return R.success("删除成功");
    }
}
@PutMapping()
    public R update(HttpServletRequest request,@RequestBody Category category){
//        LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
       if (categoryService.updateById(category)){
           return R.success("修改成功");
       }
       return R.error("修改失败");
}
@GetMapping("/list")
    public R<List<Category>> getlist(Category category){
        LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType()).orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
    List<Category> list = categoryService.list(lqw);
    return R.success(list);
}
}
